package user

import (
	"context"
	"errors"
	"gitee.com/bobo-rs/idea-space-framework/enums"
	"gitee.com/bobo-rs/idea-space-framework/pkg/core/models"
	"gitee.com/bobo-rs/idea-space-framework/pkg/core/services/safety"
	"gitee.com/bobo-rs/idea-space-framework/pkg/exception"
	"gitee.com/bobo-rs/idea-space-framework/pkg/utils"
)

// ParseUserForgotPwdParam 解析用户找回密码参数
func (u *sUser) ParseUserForgotPwdParam(ctx context.Context, item models.UserForgotPwdParseItem) (mobile string, err error) {
	// 解密参数
	safeService := safety.New()
	sign, err := safeService.Verify(
		ctx, item.Sign, enums.SafeTagsForgotPwd, item.IsRemove,
	)
	if err != nil {
		return ``, exception.New(err.Error())
	}

	// 解密手机号
	buff, err := safeService.Decrypt(item.Mobile, sign.Secret)
	if err != nil {
		return ``, exception.New(err.Error())
	}

	// 验证手机号格式
	mobile = string(buff)
	if utils.IsMobile(mobile) == false {
		return ``, exception.New(`手机号格式错误`)
	}
	return mobile, nil
}

// ForgotPwdValidate 找回密码-检验规则
func (u *sUser) ForgotPwdValidate(ctx context.Context, item models.ForgotPwdValidateItem) (result *models.ForgotPwdValidateResultItem, err error) {
	result = &models.ForgotPwdValidateResultItem{}
	// 销毁缓存
	defer func() {
		if item.IsRemove {
			_ = u.RemoveForgotPwdMac(ctx)
			_ = u.RemoveForgotPwdCaptcha(ctx, result.Mobile)
		}
	}()

	// 读取手机号
	result.Mobile, err = u.GetForgotPwdMac(ctx)
	if err != nil {
		return nil, exception.New(`找回密码-请先发送短信验证码`)
	}

	// 找回密码-最后一步修改密码，验证短信验证码是否验证通过
	if item.Step == 1 {
		b, err := u.GetForgotPwdCaptcha(ctx, result.Mobile)
		if err != nil {
			return nil, exception.NewCode(enums.ErrorForgotNotCaptcha, `找回密码-请先校验短信验证码或已过期`)
		}
		// 是否有效
		if b == false {
			return nil, exception.NewCode(enums.ErrorForgotNotCaptcha, `找回密码-验证码校验不通过`)
		}
	}
	return
}

// SetForgotPwdCache 找回密码-按步骤设置缓存检验规则
func (u *sUser) SetForgotPwdCache(ctx context.Context, mobile string, step byte) (err error) {
	// 找回密码-按步骤设置检验码
	switch step {
	case 0:
		// 发送验证码
		err = u.SetForgotPwdMac(ctx, mobile)
	case 1:
		// 校验验证码
		err = u.SetForgotPwdCaptcha(ctx, mobile)
	default:
		err = errors.New(`找回密码-未知流程`)
	}
	if err != nil {
		return exception.New(err.Error())
	}
	return nil
}
